<template>
	<view class="invite-wrapper">
		<view class="page-wrap">
			<view class="page-inner">
				<canvas canvas-id="canvasRef"
					:style="{margin:'0 auto', width: canvasWidth + 'px', height: canvasHeight + 'px' }" />
			</view>
		</view>
		<view class="footer-btn" hover-class="is-hover" @click="handleConfirm">
			<text>保存海报</text>
		</view>
		<view class="hidden-scope">
			<canvas canvas-id="qrCode" style="visibility: hidden;width: 200rpx;height: 200rpx;position: absolute" />
		</view>
	</view>
</template>

<script>
	import uQRCode from "@/utils/uqrcode";
	import { mapGetters } from "vuex";
	import { request, createShareUrl, shareType, showLoading, toast } from "@/utils/tool";
	import { center } from '@/utils/index.js'
	// 750 1360
	//https://dev.xiaonengshou.com.cn/share/zsx?activityId=201&referrerId=28&schoolId=1
	export default {
		data() {
			return {
				content: [],
				showModal: true,
				canvasWidth: 0,
				canvasHeight: 0,
				shareImage: "",
				shareTitle: "",
				shareDesc: "",
				accept: 0.55,
				scaleRatio: 0,
				// 分享图开始位置
				position: {
					shareImageStart: 75,
					shareImageEnd: 700,
					lineTop: 967,
					shareImageLeft: 60,
				},
				activitySchoolId: "",
				avatarUrl: "https://20250520wtjsq.xinyunweb.com/uploads/images/20250711/20250711222113642ec4702.png",
				userName: "王德法",
				userInfo: {}
			}
		},
		methods: {
			async getUserInfo() {
				const resp = await center()
				return resp.data
			},
			authorize() {
				return new Promise((resolve, reject) => {
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success: () => {
							resolve()
						},
						fail: res => { //这里是用户拒绝授权后的回调
							console.log('拒绝授权')
							reject()
						}
					})
				})
			},
			initSys() {
				const sys = uni.getSystemInfoSync()
				const { windowWidth, windowHeight } = sys
				const width = windowWidth
				// const height = windowHeight * 0.88
				this.canvasWidth = width
				// this.canvasHeight = width + (width * this.accept)
				this.canvasHeight = windowHeight - 100
				this.scaleRatio = width / 750
				// console.log(this.scaleRatio, 'scaleRatio')
			},

			getCanvasCtx() {
				return new Promise(resolve => {
					const query = uni.createSelectorQuery()
					query.select('#posterCanvas').fields({ node: true, size: true }).exec(resp => {
						const canvas = resp[0].node
						if (canvas.getContext) return resolve(canvas.getContext('2d'))
						return resolve(uni.createCanvasContext('canvasRef', this))
					})
				})
			},

			async initCanvas(userInfo) {
				const { avatar, nickname, id: userId } = userInfo
				const canvasBg =
					"https://20250520wtjsq.xinyunweb.com/uploads/images/20250803/20250803223700254cf8813.png"
				const { canvasWidth, canvasHeight, shareImage, shareDesc, shareTitle, scaleRatio } = this
				const position = this.position
				// const ctx = await this.getCanvasCtx()
				const ctx = uni.createCanvasContext('canvasRef', this)
				// 绘制背景图片
				await this.drawImage(canvasBg, {
					x: 0,
					y: 0,
					w: canvasWidth,
					h: canvasHeight,
					ctx,
				})
				const shareImageHeight = scaleRatio * (position.shareImageEnd - position.shareImageStart)
				const shareTop = scaleRatio * position.shareImageStart
				// 绘制分享图
				const left = scaleRatio * (position.shareImageLeft)
				// await this.drawImage(shareImage, {
				// 	x: left,
				// 	y: shareTop,
				// 	w: canvasWidth - (left * 2),
				// 	h: shareImageHeight,
				// 	ctx
				// })
				if (avatar) {
					await this.drawImage(avatar, {
						x: (canvasWidth / 2 - 30),
						y: 10,
						w: 60,
						h: 60,
						ctx
					})
				}
				// const titleHeight = shareImageHeight + shareTop + 28
				// // 绘制标题
				// this.drawText(shareTitle, { ctx, x: 35, y: titleHeight, fontSize: 18 })
				// const descHeight = titleHeight + 20
				// // 绘制描述
				// if (shareDesc) {
				// 	this.drawText(`活动描述:${shareDesc}`, { ctx, x: 35, y: descHeight, fontSize: 14 })
				// }
				// 生成二维码
				const qrCodePath = await this.createQcCode({
					id: userId,
				})
				const qrCodeHeight = canvasHeight * 0.76
				// 设置图片坐标及大小，括号里面的分别是（图片路径，x坐标，y坐标，width，height）
				ctx.drawImage(qrCodePath, (canvasWidth / 2 - 28), qrCodeHeight, 70, 70)
				ctx.draw(true) //绘制
				this.drawText(nickname, {
					ctx,
					x: canvasWidth / 2 - (nickname.length * 5.5),
					y: 94,
					fontSize: 20,
					color: "#17465C"
				})
				this.drawText("推荐您使用智小满净水服务", {
					ctx,
					x: canvasWidth / 2 - 86,
					y: 115,
					fontSize: 14,
					color: "#17465C"
				})
				return true
			},
			drawText(text, { ctx, x, y, fontSize, color }) {
				ctx.fillStyle = color || '#fc9d53';
				ctx.font = `normal ${fontSize}px sans-serif`;
				ctx.fillText(text, x, y);
				ctx.draw(true);
			},
			drawImage(url, { ctx, x, y, w, h }) {
				return new Promise(resolve => {
					uni.getImageInfo({
						src: url,
						fail: error => {
							console.log(error, 'error');
						},
						success: res => {
							console.log(res.path)
							ctx.drawImage(res.path, x, y, w,
								h) // 设置图片坐标及大小，括号里面的分别是（图片路径，x坐标，y坐标，width，height）
							// ctx.save();//保存
							ctx.draw(true) //绘制
							resolve()
						}
					})
				})
			},
			canvasToImage() {
				return new Promise(resolve => {
					uni.canvasToTempFilePath({ // 保存canvas为图片
						canvasId: 'canvasRef',
						quality: 1,
						complete: res => {
							resolve(res.tempFilePath)
						},
					})
				})
			},
			getSetting({ success, fail }) {
				uni.getSetting({
					success: ev => {
						const status = ev.authSetting['scope.writePhotosAlbum']
						if (!status) {
							this.authorize().then(() => {
								success && success()
							}).catch(() => {
								uni.showModal({
									title: "温馨提示",
									content: "您未授权了保存到本地的权限,是否前往设置?",
									showCancel: true,
									success: ev => {
										if (ev.cancel) return
										wx.openSetting({
											success: (res) => {
												console.log(res.authSetting)
												if (!res.authSetting[
														'scope.writePhotosAlbum'
													]) {
													fail && fail()
													wx.showToast({
														title: '您未授权',
														icon: 'none',
														duration: 1500
													})
												} else { // 接受授权
													success && success()
												}
											}
										})
									}
								})
							})

						} else {
							// 保存图片到系统相册
							success && success()
						}
					}
				})
			},
			saveImage(filePath) {
				this.getSetting({
					success: () => {
						wx.saveImageToPhotosAlbum({
							filePath,
							success: () => {
								toast({ title: "保存到相册了" })
							},
							fail: (res) => {
								console.log(res.errMsg)
							}
						})
					},
					fail: () => {
						toast({ title: "请授权保存图片" })
					}
				})

			},
			async handleConfirm() {
				const path = await this.canvasToImage()
				if (!path) return toast({ title: "生成海报失败" })
				this.saveImage(path)
			},
			createQcCode(payload) {
				const text = createShareUrl("/invite", payload)
				return new Promise(resolve => {
					uQRCode.make({
						canvasId: 'qrCode',
						text,
						size: 90,
						margin: 0,
						success: res => {
							resolve(res)
						},
					})
				})
			},
			async initData(activityId) {
				const h = showLoading("正在生成海报")
				const userInfo = await this.getUserInfo()
				this.userInfo = userInfo
				console.log(this.userInfo, 'userInfo@@@');
				await this.initCanvas(userInfo)
				h()
			}
		},
		onLoad(ev) {
			const { id } = ev
			this.id = id
			this.initSys()
			this.initData(id)
		},
		computed: {
			...mapGetters(["userInfo"])
		},
		onShareTimeline() {
			const { id } = this.userInfo
			const { shareImage, shareTitle, shareDesc, activitySchoolId } = this
			return {
				title: "水管家",
				// imageUrl: shareImage,
				desc: "邀请提货开单",
				type: shareType,
				path: `/pages/index/take-order/invite?guanjia_user_id=${id}&type=2`
			}
		},
		onShareAppMessage() {
			const { id } = this.userInfo
			const { shareImage, shareTitle, shareDesc, activitySchoolId } = this
			return {
				title: "水管家",
				// imageUrl: shareImage,
				desc: "邀请提货开单",
				type: shareType,
				path: `/pages/index/take-order/invite?guanjia_user_id=${id}&type=2`
			}
		},
	}
</script>


<style lang="scss" scoped>
	.invite-wrapper {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		position: relative;
		display: flex;
		flex-flow: column;
		padding-bottom: env(safe-area-inset-bottom);

		.hidden-scope {
			position: absolute;
			left: -1000rpx;
			top: -1000rpx;
		}

		.footer-btn {
			line-height: 92rpx;
			text-align: center;
			color: #ffffff;
			font-size: 40rpx;
			margin: 0 88rpx;
			box-sizing: border-box;
			height: 92rpx;
			border-radius: 46rpx 46rpx 46rpx 46rpx;
			background: linear-gradient(90deg, #7FA7E7 0%, #0A67FD 100%);

			&.is-hover {
				opacity: .8;
			}
		}

		.page-wrap {
			width: 100%;
			flex: 1;
			position: relative;

			.page-inner {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				bottom: 0;
				right: 0;
			}
		}
	}
</style>